import Opt from '@/components/dt/info/Opt.js'
import houseOpt from '@/biz/option/house.js'
import toolMgr from '@/biz/base/tool.js'
import userApi from '@/config/server/api/user.js'

class SearchOpt extends Opt {
  constructor() {
    super()
    this.workList = []
    this.build()
  }

  build() {
    this.createAll()
    this.opts.push(...this.all)
  }

  getOaPeople(workNo) {
    if (!workNo.replace(/\s+/g, '').length) {
      return new Promise((resovle, reject) => {
        resovle()
      }).then((res) => {
        this.workList = []
        return this.workList
      })
    } else {
      return userApi.teams.getByWorkNoOrName
        .fetch({
          searchKey: workNo,
          validate: 3
        })
        .then((res) => {
          this.workList = res.map((item) => {
            item.key = item.userId
            item.value = item.userName + '（' + item.workNo + '）'
            return item
          })
          return this.workList
        })
    }
  }

  createAll() {
    this.all = [
      this.organization(),
      houseOpt.create({
        to: (info) => {
          return {
            housesId: info.housesId,
            companyId: info.companyId,
            housesName: info.housesName
          }
        }
      }),
      {
        title: '工号/姓名',
        key: 'userId',
        placeholder: '请输入人员姓名或工号',
        select: {
          options: this.workList.length > 0 ? this.workList : [],
          clearable: true,
          filterable: true,
          remote: (key) => {
            return this.getOaPeople(key)
          }
        }
      }
    ]
  }

  organization() {
    let orgs = []
    let opt = {
      key: 'orgIds',
      title: '所属组织',
      tree: {
        options: orgs,
        saveParent: true,
        saveAll: false,
        maxTagCount: 2
      }
    }
    toolMgr.organization(2).then((res) => {
      orgs = res
      opt.tree.options = orgs
    })
    return opt
  }
}

export default SearchOpt
